package cn.hacynn.nd.task;

import cn.hacynn.nd.common.enumeration.ShareStatus;
import cn.hacynn.nd.mapper.ShareMapper;
import cn.hacynn.nd.pojo.entity.Share;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * @Author Hacynn
 * @Date 2024/6/2 15:17
 * @Version 1.0
 * 自定义定时任务类, 定时处理分享的文件状态
 */
@Component
@Slf4j
public class ShareTask {

    @Autowired
    private ShareMapper shareMapper;

    /**
     * 处理分享过期的文件
     */
    @Scheduled(cron = "0 * * * * ? ")  // 每分钟触发一次
    public void shareTimeOut() {
        log.info("定时处理分享过期文件:{}", new Date());

        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();

        // 查询过期订单
        List<Share> shares = shareMapper.selectList(new QueryWrapper<Share>()
                .le("expire_time", now)
                .eq("has_expired", false)
                .eq("status", ShareStatus.NORMAL.getCode()));  // 是正常分享状态的才需要处理，如果文件不存在了不需要改
        if (shares.isEmpty()) {
            return;
        }

        // 处理过期订单
        int count = 0;
        for (Share share : shares) {
            share.setStatus(ShareStatus.DESABLED.getCode());  // 过期
            share.setHasExpired(true);
            shareMapper.updateById(share);
            count++;
        }
        log.info("处理了‘{}’个过期文件", count);
    }
}
